#!/bin/bash

#应用名称
APP_NAME=ldn-server-manage.jar
#基础地址
BASE_NAME=`pwd`
#web执行地址
WEB_NAME=$BASE_NAME/$APP_NAME
# lib地址
LIB_NAME=$BASE_NAME/lib

# log日志地址
LOG_PATH=./ldn.log

if [ "$1" = "" ];
then
    echo -e "\033[0;31m 未输入操作名 \033[0m  \033[0;34m {start|stop|restart|status} \033[0m"
    exit 1
fi

#启动项目
function start ()
{
    PID=`ps -ef |grep java|grep $WEB_NAME|grep -v grep|awk '{print $2}'`

	if [ x"$PID" != x"" ]; then
	    echo "$WEB_NAME is running..."
	else
		nohup java -Dloader.path=$LIB_NAME -jar $WEB_NAME >/dev/null 2>&1 &
		sleep 3
		status
	fi
}

# 停止项目
function stop ()
{
    echo "Stop $WEB_NAME"

	PID=""
	query(){
		PID=`ps -ef |grep java|grep $WEB_NAME|grep -v grep|awk '{print $2}'`
	}

	query
	if [ x"$PID" != x"" ]; then
		kill -15 $PID
		echo "$WEB_NAME (pid:$PID) exiting..."
		while [ x"$PID" != x"" ]
		do
			sleep 1
			query
		done
		echo "$WEB_NAME exited."
	else
		echo "$WEB_NAME already stopped."
	fi
}

#重起项目
function restart()
{
    stop
	echo "$WEB_NAME is starting..."
    sleep 3
    start
}

#查看项目状态
function status()
{
    PID=`ps -ef |grep java|grep $WEB_NAME|grep -v grep|wc -l`
    if [ $PID != 0 ];then
        echo "$WEB_NAME is running..."
    else
        echo "$WEB_NAME is not running..."
    fi
}

#实施监控日志
function log()
{
	tail -n 20 -f $LOG_PATH
}

#查看日志 less命令
function less()
{
	less -i -N $LOG_PATH
}

case $1 in
    start)
    start;;
    stop)
    stop;;
    restart)
    restart;;
    status)
    status;;
    log)
    log;;
    less)
    less;;
    *)

esac
